package com.bms.admin.base.user.service.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bms.admin.base.menu.entity.Menu;
import com.bms.admin.base.menu.mapper.MenuMapper;
import com.bms.admin.base.user.entity.User;
import com.bms.admin.base.user.mapper.UserMapper;
import com.bms.admin.base.user.service.IUserService;
import com.feilong.core.Validator;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author xj
 * @since 2018-08-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private MenuMapper menuMapper;

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED)
	public Page<User> queryByPage(Page<User> page, Wrapper<User> wrapper) {
		page.setRecords(userMapper.queryByPage(page, wrapper));
		return page;
	}

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED)
	public User queryById(Long id) {
		return userMapper.queryById(id);
	}

	@Override
	public void deleteByIds(List<Long> ids) {
		User user = new User();
		user.setStatus(2);
		userMapper.update(user, new EntityWrapper<User>().in("id", ids));
	}

	@Override
	public Set<String> getUserPermissions (Long userId) {

		List<String> permsList;
		List<Menu> menuList;
		if (new Long(1).equals(userId)) {
			menuList = menuMapper.queryMenuList();
		} else {
			menuList = menuMapper.queryByUserId(userId);
		}
		permsList = menuList.stream().map(menu -> menu.getPerms()).collect(Collectors.toList());
		return permsList.stream().filter(perms -> Validator.isNotNullOrEmpty(perms)).map(perms -> Arrays.asList(perms.trim().split(","))).collect(HashSet::new, Set::addAll, Set::addAll);

	}

}
